package com.hongyi.app.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hongyi.app.entity.Permission;
import com.hongyi.app.entity.User;
import com.hongyi.app.mapper.PermissionMapper;
import com.hongyi.app.mapper.RolePermissionMapper;
import com.hongyi.app.service.PermissionService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HongYi
 */
@Slf4j
@Data
public class PermissionServiceImpl implements PermissionService {
    private PermissionMapper permissionMapper;
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Permission> list() {

        List<Permission> permissions = permissionMapper.selectList();
        return permissions != null ? permissions : new ArrayList<>();
    }

    @Override
    public boolean checkTitle(String title) {

        return permissionMapper.selectByTitle(title) != null;
    }

    @Override
    public Permission selectById(Integer id) {
       Permission permission = permissionMapper.selectById(id);
        return permission != null?permission:new Permission() ;
    }

    @Override
    public int insert(Permission permission) {

        return permissionMapper.insert(permission);
    }

    @Override
    public int updateById(Permission permission) {

        return permissionMapper.updateById(permission);
    }


    @Override
    public int deleteById(Integer id) {


        if(rolePermissionMapper.deleteByPermissionId(id)<=0){
            throw new RuntimeException("中间表记录删除失败");
        }

        if(permissionMapper.deleteById(id)<=0){
            throw new RuntimeException("permission表记录删除失败");
        }


        return 1;

    }

    @Override
    public int deleteByIds(Integer[] ids) {

        if(rolePermissionMapper.delectByPermissionIds(ids)<ids.length){
            throw new RuntimeException("中间表记录删除失败");
        }

        if(permissionMapper.delectByIds(ids)<=0){
            throw new RuntimeException("permission表记录删除失败");
        }
        return 1;
    }

    @Override
    public PageInfo<Permission> paging(Integer num, Integer size) {
        PageHelper.startPage(num,size);
        List<Permission> list = permissionMapper.selectList();
        if(list != null ){
            return  new PageInfo<>(list);
        }

        return new PageInfo<>();
    }
}
